package com.tulingxueyuan.mall.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.tulingxueyuan.mall.dto.OssPolicyResult;
import com.tulingxueyuan.mall.service.OssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * oss上传管理Service实现类
 * Created on 2018/5/17.
 */
@Service
@Slf4j
public class OssServiceImpl implements OssService {
    @Value("${aliyun.oss.accessKeyId}")
    private String accessId;
    // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    // 填写Bucket名称，例如examplebucket。
    @Value("${aliyun.oss.bucketName}")
    private String bucket;
    // 设置上传到OSS文件的前缀，可置空此项。置空后，文件将上传至Bucket的根目录下。
    @Value("${aliyun.oss.dir.prefix}")
    private String dir;
    // 提交节点
    @Value("${aliyun.oss.host}")
    private String host;

    @Resource
    private OSSClient client;

    @Override
    public OssPolicyResult policy() {
        OssPolicyResult result=new OssPolicyResult();
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            result.setAccessKeyId(client.getCredentialsProvider().getCredentials().getAccessKeyId());
            result.setPolicy(encodedPolicy);
            result.setSignature(postSignature);
            result.setDir(dir);
            result.setHost(host);

        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        }

        return result;
    }
}
